package 数组题目.数组变换;

import java.util.ArrayList;
import java.util.List;

//螺旋遍历矩阵
//https://leetcode.cn/problems/spiral-matrix/description/
class 螺旋遍历矩阵 {
    public List<Integer> spiralOrder(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        List<Integer> ans = new ArrayList<>();
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        while (ans.size() < m * n) {
            // 从左到右
            if (top <= bottom) {
                for (int i = left; i <= right; i++) {
                    ans.add(matrix[top][i]);
                }
                top++;
            }
            // 从上到下
            if (right >= left) {
                for (int i = top; i <= bottom; i++) {
                    ans.add(matrix[i][right]);
                }
                right--;
            }
            // 从右到左
            if (bottom >= top) {
                for (int i = right; i >= left; i--) {
                    ans.add(matrix[bottom][i]);
                }
                bottom--;
            }
            // 从下到上
            if (right >= left) {
                for (int i = bottom; i >= top; i--) {
                    ans.add(matrix[i][left]);
                }
                left++;
            }
        }
        return ans;
    }

//    public static void main(String[] args) {
//        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}};
//        System.out.println(new SpiralOrder().spiralOrder(matrix));
//    }
}
